﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.MobileControls;

namespace jqMvcGrid.Models
{
    public class ProductRepository : BaseDataContext, IProductRepository
    {

        #region IProductRepository Members

        public bool Create(Product product)
        {
            try
            {
                Northwind.Products.InsertOnSubmit(product);
                Northwind.SubmitChanges();
                return true;
            }
            catch { return false; }
        }

        public Product Details(int productId)
        {
            try
            {
                return Northwind.Products.Single(p => p.ProductID == productId);
            }
            catch { return null; }
        }

        public bool Edit(Product product)
        {
            try
            {
                var entity = Details(product.ProductID);
                entity.ProductName = product.ProductName;
                entity.UnitPrice = product.UnitPrice;
                // other properties
                Northwind.SubmitChanges();
                return true;
            }
            catch { return false; }
        }

        public bool Delete(int productId)
        {
            try
            {
                Northwind.Products.DeleteOnSubmit(Details(productId));
                return true;
            }
            catch { return false; }
        }

        public IQueryable<Product> Index()
        {
            try
            {
                var products = Northwind.Products.ToList();
                return products.AsQueryable();
            }
            catch { return null; }
        }

        public IQueryable<Product> Index(int categoryId)
        {
            try
            {
                return Northwind.Products.Where(p => p.CategoryID == categoryId).AsQueryable();
            }
            catch { return null; }
        }

        #endregion
    }

    public interface IProductRepository
    {
        bool Create(Product product);
        Product Details(int productId);
        bool Edit(Product product);
        bool Delete(int productId);
        IQueryable<Product> Index();
        IQueryable<Product> Index(int categoryId);
    }
}
